﻿using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;

public class ExcelImporter
{
    private static bool CanImport(string filePath)
    {
        <CanImport>c__AnonStorey93 storey = new <CanImport>c__AnonStorey93 {
            filePath = filePath
        };
        string[] source = new string[] { ".xls" };
        return (source.FirstOrDefault<string>(new Func<string, bool>(storey.<>m__1A3)) != null);
    }

    public static void ImportAsCsv(string filePath)
    {
        if (CanImport(filePath))
        {
            string directoryName = Path.GetDirectoryName(filePath);
            string destFileName = filePath + "_" + Guid.NewGuid().ToString();
            File.Copy(filePath, destFileName);
            using (FileStream stream = File.Open(destFileName, FileMode.Open, FileAccess.Read))
            {
                IWorkbook workbook = new HSSFWorkbook(stream);
                for (int i = 0; i < workbook.NumberOfSheets; i++)
                {
                    ISheet sheetAt = workbook.GetSheetAt(i);
                    string path = directoryName + "/" + sheetAt.SheetName + ".csv";
                    string contents = sheetAt.ToCsvString();
                    File.WriteAllText(path, contents);
                }
                File.Delete(destFileName);
            }
        }
    }

    public static IWorkbook Load(string filePath)
    {
        IWorkbook workbook;
        if (!CanImport(filePath))
        {
            return null;
        }
        string destFileName = filePath + "_" + Guid.NewGuid().ToString();
        File.Copy(filePath, destFileName);
        using (FileStream stream = File.Open(destFileName, FileMode.Open, FileAccess.Read))
        {
            workbook = new HSSFWorkbook(stream);
            File.Delete(destFileName);
        }
        return workbook;
    }

    [CompilerGenerated]
    private sealed class <CanImport>c__AnonStorey93
    {
        internal string filePath;

        internal bool <>m__1A3(string x)
        {
            return (x == Path.GetExtension(this.filePath));
        }
    }
}

